<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\controller\WXBizDataCrypt;
use think\Exception;

class Login extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ["*"];

    protected array $params;

    public function __construct()
    {
        parent::__construct();
        $this->params = array_filter(array_merge($this->request->post(), $this->request->get()));
    }

    /**
     * 微信小程序登录
     * */
    public function weChatLogin()
    {
        try {
            $validate = $this->validate($this->params, 'app\\api\\validate\\Login.weChatLogin');
            if ($validate !== true) {
                throw new Exception($validate);
            }

            // 获取小程序登录
            $url = 'https://api.weixin.qq.com/sns/jscode2session';
            $requestParam = [
                'appid' => config('site.appid'),
                'secret' => config('site.secret'),
                'js_code' => $this->params['js_code'],
                'grant_type' => 'authorization_code'
            ];
            $requestResult = http_query_url($url, 'get', $requestParam);
            if (!empty($requestResult['errcode'])) {
                throw new Exception('小程序授权错误，【code：' . $requestResult['errcode'] . '】，【描述：' . $requestResult['errmsg'] . '】');
            }
            // 解析微信密文数据，得到用户信息
            $pc = new WXBizDataCrypt(config('site.appid'), $requestResult['session_key']);
            $errCode = $pc->decryptData($this->params['encryptedData'], $this->params['iv'], $data);
            if ($errCode != 0) {
                throw new Exception('小程序授权异常');
            }
            $user_id = (new \app\common\model\User)->login($data);
            if ($this->auth->direct($user_id)) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 绑定手机号
     * */
    public function bindMobile()
    {
        try {
            $validate = $this->validate($this->params, 'app\\api\\validate\\Login.bindMobile');
            if ($validate !== true) {
                throw new Exception($validate);
            }
            $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $this->getAccessToken()['access_token'];
            $requestParam = json_encode(['code' => $this->params['code']]);
            $request = http_query_url($url, 'post', $requestParam);
            if (!empty($request['errcode'])) {
                throw new Exception('小程序授权错误，【code：' . $request['errcode'] . '】，【描述：' . $request['errmsg'] . '】');
            }
            $user_id = (new \app\common\model\User)->bindMobile(array_merge($request['phone_info'], ['openid' => $this->params['openid']]));
            if ($ret = $this->auth->direct($user_id)) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * @throws Exception
     * */
    protected function getAccessToken()
    {
        $request = http_query_url('https://api.weixin.qq.com/cgi-bin/token', 'get', [
            'grant_type' => 'client_credential',
            'appid' => config('site.appid'),
            'secret' => config('site.secret'),
        ]);
        if (!empty($request['errcode'])) {
            throw new Exception('小程序授权错误，【code：' . $request['errcode'] . '】，【描述：' . $request['errmsg'] . '】');
        }
        return $request;
    }
}